package com.itheima.aspect;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class EmpLoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;


    @Around("execution(* com.itheima.controller.LoginController.login(*))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //执行原方法
        long begin = 0;
        long end = 0 ;
        Object proceed = null;
        Integer success = 1;
        try {
            begin = System.currentTimeMillis();
            proceed = pjp.proceed();
            end = System.currentTimeMillis();
        } catch (Throwable e) {
            success = 0;
            throw e;
        } finally {
            try {
                EmpLoginLog empLoginLog = new EmpLoginLog();
                //获取返回data
                Result result = (Result) proceed;
                if (result != null){
                    Object data = result.getData();
                    LoginInfo loginInfo = (LoginInfo) data;
                    if (loginInfo != null){
                        empLoginLog.setJwt(((LoginInfo) data).getToken());
                    }
                }
                //获取请求参数
                Object[] args = pjp.getArgs();
                Emp emp = (Emp) args[0];
                empLoginLog.setUsername(emp.getUsername());
                empLoginLog.setPassword(emp.getPassword());
                empLoginLog.setLoginTime(LocalDateTime.now());
                empLoginLog.setIsSuccess(success.shortValue());
                empLoginLog.setCostTime(end - begin <0 ? 0 : (end - begin));
                empLoginLogMapper.insert(empLoginLog);
            } catch (Exception e) {
                log.error("记录登录日志出现异常",e);
            }
        }
        return proceed;
    }
}
